<template>
  <PageWrapper>
    <a-card>
      <div class="container contents">
        <a-row>
          <a-col :span="18"></a-col>
          <a-col :span="6">
            <a-range-picker
              v-model="selectDate"
              :showTime="true"
              format="YYYY/MM/DD HH:mm:ss"
              :ranges="timeRanges"
              @ok="selectDateOk"
            />
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-card>
              <iframe title="topReqRateIframe" class="panelIframe" :src="topReqRateIframeUrl" frameborder="0"></iframe>
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-card>
              <iframe
                title="topServerErrRateIframe"
                class="panelIframe"
                :src="topServerErrRateIframeUrl"
                frameborder="0"
              ></iframe>
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-card>
              <iframe
                title="topRespLatencyIframe"
                class="panelIframe"
                :src="topRespLatencyIframeUrl"
                frameborder="0"
              ></iframe>
            </a-card>
          </a-col>
        </a-row>
        <a-card>
          <a-row>
            <a-col :span="18">
              <a-input
                v-model="input"
                placeholder="请输入应用名"
                @input="handleInput"
                @clear="handleClear"
                style="width: 30%"
                clearable
              >
              </a-input
            ></a-col>
          </a-row>

          <a-table :columns="tableColumns" :data-source="tableData" :customRow="rowclick" rowKey="id"> </a-table>
        </a-card>
      </div>
      <a-drawer
        :title="drawerTitle"
        :visible="drawer"
        @close="handleClose"
        :width="drawerWidth"
        :destroyOnClose="true"
        :getContainer="false"
      >
        <appDetail
          :isShow="showAppDetail"
          :machine_id="machine_id"
          :podId="podId"
          :tgid="tgid"
          :windowWidth="drawerWidth"
          :objectType="objectType"
          :objectId="objectId"
          :startTimestamp="startTimestamp"
          :endTimestamp="endTimestamp"
        />
      </a-drawer>
    </a-card>
  </PageWrapper>
</template>

<script>
import { api } from '@/api'
import {
  getReqRate,
  getRespRate,
  getServerExceptionRate,
  getServerRespLatency,
  getClientReqLatency,
  getTopReqRateObjectList,
  getTopServerErrRateObjectList,
  getTopRespLatencyObjectList
} from '@/views/app/req';
import dayjs from 'dayjs';
import appDetail from './appDetail.vue'
import { timeRanges } from './components'
import PageWrapper from '@/components/PageWrapper.vue'

export default {
  name: 'MetricsInfo',
  components: { PageWrapper, appDetail},
  data() {
    return {
      tableData: [],
      tempData: [],
      input: '',
      drawer: false,
      drawerWidth: 0,
      direction: 'rtl',
      showAppDetail: false,
      machine_id: '',
      podId: '',
      tgid: '',
      drawerTitle: '',
      objectId: '',
      objectType: '',
      tableColumns: [
        {
          title: '应用',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '主机',
          dataIndex: 'job',
          key: 'job'
        },
        {
          title: '请求速率',
          dataIndex: 'reqRate',
          key: 'reqRate'
        },
        {
          title: '应答速率',
          dataIndex: 'respRate',
          key: 'respRate'
        },
        {
          title: '服务端异常比例',
          dataIndex: 'serverExceptionRate',
          key: 'serverExceptionRate'
        },
        {
          title: '请求时延',
          dataIndex: 'reqLatency',
          key: 'reqLatency'
        },
        {
          title: '响应时延',
          dataIndex: 'respLatency',
          key: 'respLatency'
        }
        // {
        //   title: 'TCP时延',
        //   dataIndex: 'tcpLatency',
        //   key: 'tcpLatency'
        // },
        // {
        //   title: 'IO wait',
        //   dataIndex: 'iowait',
        //   key: 'iowait'
        // },
        // {
        //   title: 'CPU',
        //   dataIndex: 'cpuUtil',
        //   key: 'cpuUtil'
        // }
      ],
      topReqRateChart: {},
      topServerErrRateChart: {},
      topRespLatencyChart: {},
      selectDate: [],
      topReqRateIframeUrl: '',
      topServerErrRateIframeUrl: '',
      topRespLatencyIframeUrl: '',
      startTimestamp: 0,
      endTimestamp: 0,
      timeRanges: timeRanges,
      grafanaServerAddr: ''
    };
  },
  computed: {},
  mounted() {
    this.initGrafanaServerAddr();
    this.initPage();
  },
  updated() {
  },
  methods: {
    async initGrafanaServerAddr() {
      // const [_, res] = await api.getGrafanaServerAddr()
      this.grafanaServerAddr = '/grafanaweb';
    },
    handleInput(val) {
      this.initTableData();
    },
    handleClear() {},
    rowclick(record, index) {
      return {
        on: {
          click: () => {
            this.drawer = true;
            this.drawerWidth = window.innerWidth * 0.865;
            this.showAppDetail = true;
            this.drawerTitle = `${record.name} 应用详情`;
            this.machine_id = record.machine_id.substr(0, 36);
            this.tgid = record.tgid;
            this.podId = record.pod_id;
            this.objectType = record.type;
            this.objectId = record.objectId;
            this.startTimestamp = this.selectDate[0].valueOf();
            this.endTimestamp = this.selectDate[1].valueOf();
          }
        }
      };
    },
    handleClose() {
      this.drawer = false;
    },
    async initTableData() {
      var param = {
        queryKeyword: this.input,
        startTime: this.selectDate[0].valueOf() / 1000,
        endTime: this.selectDate[1].valueOf() / 1000
      }
      const [_, res] = await api.getObjectList(param)

      const data = res.data.result
      var key, objectId, type, name, job
      var objectMap = new Map()
      var node

      for (const i of data) {
        const item = i.metric
        item.timestamp = this.selectDate[1].valueOf()
        if ('pod_id' in item) {
          type = 'pod'
          objectId = item.pod_id
          name = item.pod
        } else if ('container_id' in item) {
          type = 'container'
          objectId = item.container_id
          name = item.container_name
        } else if ('tgid' in item && 'comm' in item) {
          type = 'proc'
          objectId = item.tgid
          name = `${item.comm}_${item.tgid}`
        }
        key = `${item.machine_id}_${objectId}`
        job = item.job
        if (!objectMap.has(key)) {
          node = item
          node.id = key
          node.type = type
          node.objectId = objectId
          node.name = name
          node.job = job
          node.reqRate = await getReqRate(node)
          node.reqLatency = await getClientReqLatency(node)
          node.respRate = await getRespRate(node)
          node.respLatency = await getServerRespLatency(node)
          node.serverExceptionRate = await getServerExceptionRate(node)
          // node.tcpLatency = await getAppTcpLinkSrttAvg(node);
          objectMap.set(key, node)
        }


        this.tableData = [];
        for (var value of objectMap.values()) {
          this.tableData.push(value);
        }
        console.log('tableData:', this.tableData);
      }
    },
    getQueryPattern(item) {
      var queryPattern = '';
      switch (item.type) {
        case 'pod':
          queryPattern = `&var-pod_id=${item.objectId}`;
          break;
        case 'container':
          queryPattern = `&var-container_id=${item.objectId}`;
          break;
        case 'proc':
          queryPattern = `&var-tgid=${item.objectId}`;
          break;
      }
      return queryPattern;
    },
    getGapQueryStr(querypattern) {
      var res = '';
      if (querypattern.indexOf('pod_id') === -1) {
        res += '&var-pod_id=-1';
      }
      if (querypattern.indexOf('container_id') === -1) {
        res += '&var-container_id=-1';
      }
      if (querypattern.indexOf('tgid') === -1) {
        res += '&var-tgid=-1';
      }
      return res;
    },
    async initTopPanels() {
      var queryPattern1 = '';
      var queryPattern2 = '';
      var queryPattern3 = '';
      var item;
      const startTimestamp = this.selectDate[0].valueOf();
      const endTimestamp = this.selectDate[1].valueOf();
      const param = {
        startTimestamp: startTimestamp / 1000,
        endTimestamp: endTimestamp / 1000
      }
      var topReqRateObjectList = await getTopReqRateObjectList(param);
      var topServerErrRateObjectList = await getTopServerErrRateObjectList(param);
      var topRespLatencyObjectList = await getTopRespLatencyObjectList(param);

      for (item of topReqRateObjectList) {
        queryPattern1 += this.getQueryPattern(item);
      }
      queryPattern1 += this.getGapQueryStr(queryPattern1);

      for (item of topServerErrRateObjectList) {
        queryPattern2 += this.getQueryPattern(item);
      }
      queryPattern2 += this.getGapQueryStr(queryPattern2);

      for (item of topRespLatencyObjectList) {
        queryPattern3 += this.getQueryPattern(item);
      }
      queryPattern3 += this.getGapQueryStr(queryPattern3);

      this.topReqRateIframeUrl = `${this.grafanaServerAddr}/d-solo/xvSeLIKIz/appdetail-appaccesspanels?orgId=1
      ${queryPattern1}&from=${startTimestamp}&to=${endTimestamp}&orgId=1&panelId=167&theme=light`;
      this.topServerErrRateIframeUrl = `${this.grafanaServerAddr}/d-solo/xvSeLIKIz/appdetail-appaccesspanels?orgId=1
      ${queryPattern2}&from=${startTimestamp}&to=${endTimestamp}&orgId=1&panelId=169&theme=light`;
      this.topRespLatencyIframeUrl = `${this.grafanaServerAddr}/d-solo/xvSeLIKIz/appdetail-appaccesspanels?orgId=1
      ${queryPattern3}&from=${startTimestamp}&to=${endTimestamp}&orgId=1&panelId=171&theme=light`;
    },
    async initPage() {
      var currTimestamp = Date.now();
      var fromTimestamp = currTimestamp - 1000 * 60 * 5;
      var query = this.$route.query;
      if (Object.keys(query).length !== 0) {
        currTimestamp = Number(query.end);
        fromTimestamp = Number(query.start);
      }
      this.selectDate.push(dayjs(fromTimestamp));
      this.selectDate.push(dayjs(currTimestamp));
      this.$router.push({
        query: {
          start: this.selectDate[0].valueOf(),
          end: this.selectDate[1].valueOf()
        }
      });
      this.initTableData();
      this.initTopPanels();
    },
    selectDateOk(e) {
      this.$router.push({
        query: {
          ...this.$route.query,
          start: this.selectDate[0].valueOf(),
          end: this.selectDate[1].valueOf()
        }
      });
      this.initTopPanels();
      this.initTableData();
    }
  }
};
</script>

<style scoped lang="less">
::v-deep {
  .panelTitle {
    width: 100%;
    text-align: center;
    margin-bottom: 5px;
  }
  .panelIframe {
    width: 100%;
    height: 200px;
  }
  .ant-card-body {
    padding-bottom: 0px;
  }
}
</style>
